package com.ruoyi.app.service.impl

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.io.FileUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.shaun.core.context.ProfileHolder
import com.ruoyi.app.common.*
import com.ruoyi.app.domain.dto.UserRecordDto
import com.ruoyi.app.domain.vo.UserRecordVo
import com.ruoyi.app.service.RecordApiService
import com.ruoyi.back.domain.UserRecord
import com.ruoyi.back.service.UserRecordService
import com.ruoyi.common.core.page.PageDomain
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.File

@Service
class RecordApiServiceImpl : RecordApiService {

    @Autowired
    private lateinit var userRecordService: UserRecordService

    override fun getUserRecordList(pageDomain: PageDomain): PageData<UserRecordVo> =
        userRecordService.page(
            Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()),
            KtQueryWrapper(UserRecord::class.java)
                .eq(UserRecord::createBy, ProfileHolder.getProfile().id)
                .orderByDesc(UserRecord::createTime)
        ).let { page: Page<UserRecord> ->
            Page<UserRecordVo>().apply {
                BeanUtil.copyProperties(page, this)
                records = page.records.takeIf { it.isNotEmpty() }
                    ?.run {
                        map {
                            UserRecordVo().apply {
                                BeanUtil.copyProperties(it, this)
                                createTime = it.createTime?.format()
                            }
                        }
                    }
            }.pageInfo()
        }

    override fun addUserRecord(userRecordDto: UserRecordDto): Data<Boolean> =
        Ok(
            "保存用户记录成功", userRecordService.save(UserRecord()
                .apply {
                    url = userRecordDto.url
                    name = userRecordDto.name ?: FileUtil.getName(File(userRecordDto.url!!))
                    duration = userRecordDto.duration
                    size = userRecordDto.size
                    createBy = ProfileHolder.getProfile().id.toLong()
                })
        )

    override fun removeUserRecord(ids: String): Data<Boolean> =
        Ok("批量移除成功", userRecordService.removeByIds(ids.split(",")))
}